package com.gxa.modules.pc.sys.usermanager.controller;

import com.gxa.common.utils.MD5Utils;
import com.gxa.common.utils.Result;
import com.gxa.modules.pc.sys.usermanager.dto.SysUserForm;
import com.gxa.modules.pc.sys.usermanager.entity.SysTUser;
import com.gxa.modules.pc.sys.usermanager.service.SysTUserService;
import com.gxa.modules.sys.entity.User;
import com.gxa.modules.sys.form.UserForm;
import com.gxa.modules.sys.service.UserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SysUserPcController
 * @Description 登录部分
 * @Author Mr.YUAN
 * @Date 2022/11/19 18:11
 */
@Api(tags = "系统登录管理")
@RestController
@RequestMapping("/sys01")
@Slf4j
public class SysUserPcController {

    @Autowired
    private SysTUserService sysTUserService;
    @Autowired
    private UserTokenService userTokenService;

    @ApiOperation("我的登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody SysUserForm user){
        log.info("------------>{}",user);
        //1.为空校验
        if(StringUtils.isAnyBlank(user.getAccount(), user.getPassword())){

            return new Result().error("用户名或密码不能为空！");
        }
        //2.根据用户名查询用户信息
        SysTUser sysTUser = sysTUserService.queryByAccount(user.getAccount());
        if(sysTUser == null){
            return new Result().error("用户名或密码错误!");
        }
        //3.将明文密码加密 与密文密码比较
        String encodePassword = MD5Utils.encrypt(user.getAccount(),user.getPassword());
        if(!encodePassword.equals(sysTUser.getUserPassword())){
            return new Result().error("用户名或密码错误!");
        }
        //4.密码相同，登录成功 创建token 放redis
        Result result = userTokenService.createToken(sysTUser);
        Map<String,Object> map = new HashMap<>();
        //Authorization 过滤器拦截
        map.put("token",result.getData());
        return new Result().ok(map);
    }
}